package com.lam.common.components.captcha.instances.kaptcha;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;

import com.google.code.kaptcha.Producer;
import com.lam.common.components.captcha.enums.CaptchaTypeEnum;
import com.lam.common.components.captcha.model.CaptchaEntry;
import com.lam.common.exception.BaseException;
import com.lam.common.utils.Base64Util;
import com.lam.common.utils.StringUtils;

@Component
public class KaptchaKit {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Resource(name = "captchaProducer")
	private Producer captchaProducer;

	@Resource(name = "captchaProducerMath")
	private Producer captchaProducerMath;
	
	public CaptchaEntry genCode(CaptchaTypeEnum captchaType) {
		
		String code = null;
		BufferedImage image = null;
		// 生成验证码
		if (CaptchaTypeEnum.MATH == captchaType) {
			String capText = captchaProducerMath.createText();
			int index = capText.lastIndexOf("@");
			code = capText.substring(index + 1);
			image = captchaProducerMath.createImage(capText.substring(0, index));
		} else if (CaptchaTypeEnum.CHAR == captchaType) {
			code = captchaProducer.createText();
			image = captchaProducer.createImage(code);
		} else {
			throw new BaseException("不支持的验证码类型");
		}

		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpg", os);
		} catch (IOException e) {
			logger.error("生成验证码异常", e);
			throw new BaseException("获取验证码失败");
		}

		return new CaptchaEntry(code, "data:image/jpeg;base64," + Base64Util.encodeByte(os.toByteArray()), captchaType.getName());
	}
	
	public boolean checkCode(String textData, String code) {
		return StringUtils.equalsIgnoreCase(textData, code);
	}

}
